package cn.jfinalbbs.utils;


/**
 * 用于向远程服务器发送request请求，此请求使用Post方式
 *
 * @author rich.chen 2012-02-27
 * 返回服务器端响应的String
 */

import com.alibaba.fastjson.JSON;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

@SuppressWarnings("all")
public class IOLHttpClient {

    private static Logger logger = Logger.getLogger(IOLHttpClient.class);

    private static MultiThreadedHttpConnectionManager connectionManager = null;

    private static HttpClient httpclient = null;

    static {
        connectionManager = new MultiThreadedHttpConnectionManager();
        httpclient = new HttpClient(connectionManager);
        //链接超时
        httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(600 * 1000);
        //读取超时
        httpclient.getHttpConnectionManager().getParams().setSoTimeout(600 * 1000);
    }

    //	将流转换成为字符串
    private static String getStringFromStream(PostMethod method) throws Exception {
        InputStream resStream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(resStream, "UTF-8"));
        StringBuffer resBuffer = new StringBuffer();
        String resTemp = "";
        while ((resTemp = br.readLine()) != null) {
            resBuffer.append(resTemp);
        }
        String response = resBuffer.toString();
        return response;
    }


    @Deprecated
    public static String post(String url, String json, Part[] parts) {
        String result = null;

        PostMethod httpost = new PostMethod(url);

        try {
            //设置编码格式统一为UTF_8
            httpost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            httpost.getParams().setContentCharset("UTF-8");
            httpost.addRequestHeader("param", json);

            httpost.setRequestEntity(new MultipartRequestEntity(parts, httpost.getParams()));
            //开始执行
            int status = httpclient.executeMethod(httpost);

            //如果状态为200，表示执行成功
            if (status == HttpStatus.SC_OK) {

                InputStream resStream = httpost.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(resStream, "UTF-8"));
                StringBuffer resBuffer = new StringBuffer();
                String resTemp = "";
                while ((resTemp = br.readLine()) != null) {
                    resBuffer.append(resTemp);
                }
                result = resBuffer.toString();
            } else {
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug(e);
            return null;
        } finally {
            httpost.releaseConnection();
            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }

    }


    public static String post(String url, String json) {
        boolean isGzip = false;
        String result = null;
        PostMethod httpost = new PostMethod(url);
        try {
            //设置参数
            httpost.setRequestBody(json);
            //设置编码格式统一为UTF_8
            httpost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

            //三种形式
            httpost.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
//			httpost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
//			httpost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            //设置超时
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);

            //开始执行
            httpclient.executeMethod(httpost);
            //如果状态为200，表示执行成功
            if (httpost.getStatusCode() == HttpStatus.SC_OK) {
                //如果是Gzip的压缩返回值
                result = getStringFromStream(httpost);
            }
            return result;
        } catch (Exception e) {
            //写入日志
            //	IOLLogWriter.writeLog(e);
            logger.debug(e);
            return null;
        } finally {
            httpost.releaseConnection();
            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }
    }


    //实现httpclient处理重定向问题

    public static String sendPostRequest(String url, Map<String, String> requestParam) {
        String result = null;
        PostMethod httpost = new PostMethod(url);
        try {

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (requestParam != null) {
                // 添加请求参数
                Iterator<String> keySetIterator = requestParam.keySet().iterator();
                while (keySetIterator.hasNext()) {
                    String key = keySetIterator.next();
                    String value = requestParam.get(key);
                    nvps.add(new NameValuePair(key, value));
                }
            }
            NameValuePair[] data = nvps.toArray(new NameValuePair[]{});
            //设置参数
            httpost.setRequestBody(data);
            //设置编码格式统一为UTF_8
            httpost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            //设置超时
            httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
            //开始执行
            httpclient.executeMethod(httpost);
            //如果状态为200，表示执行成功
            if (httpost.getStatusCode() == HttpStatus.SC_OK) {
                //如果是Gzip的压缩返回值
                result = getStringFromStream(httpost);
            }
            return result;
        } catch (Exception e) {
            //写入日志
            //	IOLLogWriter.writeLog(e);
            logger.debug(e);
            return null;
        } finally {
            httpost.releaseConnection();
            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }
    }


    public static String sendPostRequest(String url, Map<String, String> requestParam, String encode) {
        String result = null;
        PostMethod httpost = new PostMethod(url);
        try {

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (requestParam != null) {
                // 添加请求参数
                Iterator<String> keySetIterator = requestParam.keySet().iterator();
                while (keySetIterator.hasNext()) {
                    String key = keySetIterator.next();
                    String value = requestParam.get(key);
                    nvps.add(new NameValuePair(key, value));
                }
            }
            NameValuePair[] data = nvps.toArray(new NameValuePair[]{});
            //设置参数
            httpost.setRequestBody(data);
            //设置编码格式统一为UTF_8
            httpost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encode);
            //设置超时
            //httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
            //开始执行
            httpclient.executeMethod(httpost);
            //如果状态为200，表示执行成功
            if (httpost.getStatusCode() == HttpStatus.SC_OK) {
                result = getStringFromStream(httpost);
            }
            return result;
        } catch (Exception e) {
            //写入日志
            //	IOLLogWriter.writeLog(e);
            logger.debug(e);
            return null;
        } finally {
            httpost.releaseConnection();
            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }
    }

    public static String get(String url) throws IllegalStateException, IOException {
        HttpClient client = new HttpClient();
        StringBuilder sb = new StringBuilder();
        InputStream ins = null;
        // Create a method instance.
        GetMethod method = new GetMethod(url);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);
            System.out.println(statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                ins = method.getResponseBodyAsStream();
                byte[] b = new byte[1024];
                int r_len = 0;
                while ((r_len = ins.read(b)) > 0) {
                    sb.append(new String(b, 0, r_len, method
                            .getResponseCharSet()));
                }
            } else {
                System.err.println("Response Code: " + statusCode);
            }
        } catch (HttpException e) {
            System.err.println("Fatal protocol violation: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("Fatal transport error: " + e.getMessage());
        } finally {
            method.releaseConnection();
            if (ins != null) {
                ins.close();
            }
        }
        System.out.println(sb.toString());
        return sb.toString();
    }
}
